﻿using System.Collections;
using Script.UI.Msg;
using UnityEngine;
using UnityEngine.UI;

namespace Script.UI
{
    public class PromptPanel : UIBase
    {
        /// <summary>
        /// 提示面板的提示文字
        /// </summary>
        private Text promptText;

        /// <summary>
        /// 提示面板挂载的脚本
        /// 此处用于控制透明度
        /// </summary>
        private CanvasGroup canvasGroup;

        /// <summary>
        /// 提示文字显示的时间
        /// </summary>
        [SerializeField]
        [Range(0, 3)]
        private float showTime = 1f;


        /// <summary>
        /// 提示动画计算器
        /// </summary>
        private float timer;


        /// <summary>
        /// 接受包工头(UIManager) 的消息
        /// </summary>
        /// <param name="eventCode"></param>
        /// <param name="message"></param>
        public override void Execute(int eventCode, object message)
        {
            switch (UIEvent.PROMPT_MSG)
            {
                case UIEvent.PROMPT_MSG:
                {
                    PromptMsg msg = message as PromptMsg;
                    PromptMessage(msg.Text, msg.Color);
                    break;
                }
                default:
            }
        }

        // Start is called before the first frame update
        private void Start()
        {
            // 获取对象
            promptText = transform.Find("PromptText").GetComponent<Text>();
            canvasGroup = transform.Find("PromptText").GetComponent<CanvasGroup>();
        
            // 留电话号码 注册
            Bind(UIEvent.PROMPT_MSG);


            // 场景预处理
            canvasGroup.alpha = 0;
        }


        /// <summary>
        /// 提示消息
        /// </summary>
        /// <param name="text"></param>
        /// <param name="color"></param>
        private void PromptMessage(string text, Color color)
        {
            promptText.text = text;
            promptText.color = color;
            canvasGroup.alpha = 0;
            timer = 0;
            // 做动画显示

            StartCoroutine(PromptAnig());
        }

        /// <summary>
        /// 用来显示动画
        /// </summary>
        /// <returns></returns>
        IEnumerator PromptAnig()
        {
            while (canvasGroup.alpha < 1f)
            {
                canvasGroup.alpha += Time.deltaTime;
                yield return new WaitForEndOfFrame();
            }

            while (timer == showTime)
            {
                timer -= Time.deltaTime;
                yield return new WaitForEndOfFrame();
            }

            while (canvasGroup.alpha > 0)
            {
                canvasGroup.alpha -= Time.deltaTime;
                yield return new WaitForEndOfFrame();
            }
        }
    }
}
